package com.tsugun.mediaplayer.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.AlbumModel;
import com.tsugun.mediaplayer.model.entity.ArtistModel;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.presenter.utils.SettingPreferenceHelper;
import com.tsugun.mediaplayer.view.activity.BaseActivity;
import com.tsugun.mediaplayer.view.activity.IndexActivity;
import com.tsugun.mediaplayer.view.adapter.ViewPagerAdapter;
import com.tsugun.mediaplayer.view.fragment.subfragment.AlbumListFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.ArtistListFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.SongListFragment;
import com.tsugun.mediaplayer.view.fragment.subfragment.SubBaseFragment;
import com.tsugun.mediaplayer.view.widget.SlidingRelativeLayout;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 搜索界面
 * Created by shize on 2017/4/20.
 */

public class SearchFragment extends BaseFragment {

    public static final String SEARCH_TERM = "com.TsuGun.search";

    @BindView(R.id.id_sliding_body)
    SlidingRelativeLayout mSlidingLayout;
    @BindView(R.id.id_bg_night)
    RelativeLayout mBgLayout;
    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_toolbar_search_view)
    SearchView mSearchView;
    @BindView(R.id.id_layout_feature)
    RelativeLayout mRlFeature;
    @BindView(R.id.id_search_hot_list)
    RecyclerView mRvHot;
    @BindView(R.id.id_search_history_list)
    RecyclerView mRvHistory;
    @BindView(R.id.id_layout_list)
    RelativeLayout mRlList;
    @BindView(R.id.id_tab)
    TabLayout mTabLayout;
    @BindView(R.id.id_pager)
    ViewPager mViewPager;

    private View mFragment;
    private Context mContext;
    private Unbinder unbinder;
    private IndexActivity indexActivity;

    // fragment集合
    private List<SubBaseFragment> mFragments;
    private List<String> mTitles;
    // 内容提供者
    private ListProvider mProvider;
    // 各类结果集合
    private List<MusicModel> mSongs;
    private List<ArtistModel> mArtist;
    private List<AlbumModel> mAlbum;
    // 每次输入变化的字符串
    private String mNewText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mFragment != null) {
            return mFragment;
        }
        mFragment = inflater.inflate(R.layout.fragment_search, container, false);
        mContext = container.getContext();
        unbinder = ButterKnife.bind(this, mFragment);

        initView();
        initData();
        bindData();
        return mFragment;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        initPage();
    }

    /**
     * 初始化list页面
     */
    private void initPage() {
        mFragments = new ArrayList<>();
        mFragments.add(new SongListFragment());
        mFragments.add(new ArtistListFragment());
        mFragments.add(new AlbumListFragment());

        mTitles = new ArrayList<>();
        mTitles.add(getString(R.string.str_tab_song));
        mTitles.add(getString(R.string.str_tab_artist));
        mTitles.add(getString(R.string.str_tab_album));
    }

    /**
     * 初始化数据
     */
    private void initData() {
        indexActivity = (IndexActivity) mContext;
        mSongs = new ArrayList<>();
        mArtist = new ArrayList<>();
        mAlbum = new ArrayList<>();
    }

    /**
     * 绑定数据
     */
    private void bindData() {
        bindSliding();
        bindToolbar();
        bindPage();
    }

    /**
     * 绑定滑动
     */
    private void bindSliding() {
        mSlidingLayout.setOnSlidingListener(new SlidingRelativeLayout.OnSlidingListener() {
            @Override
            public void onDown() {

            }

            @Override
            public void onAnimationEnd(boolean isClose) {
                if (isClose) {
                    indexActivity.getMusicFragmentManager().backFragment();
                }
            }
        });
    }

    /**
     * 设置toolbar
     */
    private void bindToolbar() {
        final IndexActivity indexActivity = (IndexActivity) mContext;
//        indexActivity.setSupportActionBar(mToolbar);
        mProvider = indexActivity.getListProvider();
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                indexActivity.getMusicFragmentManager().backFragment();
            }
        });
        // 默认展开
        mSearchView.setIconified(false);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 提交事件
                searchData(query);
                displayResultList();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 字符发生改变事件
                mNewText = newText;
                return false;
            }
        });
        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                // 防止展开的searchView被关闭
                return (mNewText == null || mNewText.equals(""));
            }
        });
    }

    /**
     * 绑定页面
     */
    private void bindPage() {
        for (int i = 0; i < mTitles.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mTitles.get(i)));
        }
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(((IndexActivity) mContext)
                .getSupportFragmentManager(), mFragments, mTitles);
        mViewPager.setAdapter(viewPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    /**
     * 显示搜索结果列表
     */
    private void displayResultList() {
        mRlFeature.setVisibility(View.GONE);
        mRlList.setVisibility(View.VISIBLE);
        ((SongListFragment) mFragments.get(0)).setResult(mSongs);
        ((ArtistListFragment) mFragments.get(1)).setResult(mArtist);
        ((AlbumListFragment) mFragments.get(2)).setResult(mAlbum);
    }

    /**
     * 搜索相关数据
     */
    private void searchData(String query) {
        if (mProvider == null || query == null) {
            clearResult();
            return;
        }
        clearResult();
        mSongs.addAll((Collection<MusicModel>) mProvider.searchMusicBySongTitle(query));
        mArtist.addAll((Collection<ArtistModel>) mProvider.searchArtistByName(query));
        mAlbum.addAll((Collection<AlbumModel>) mProvider.searchAlbumByName(query));
    }

    /**
     * 清除结果
     */
    private void clearResult() {
        mSongs.clear();
        mArtist.clear();
        mAlbum.clear();
    }

    @Override
    public void onResume() {
        super.onResume();
        indexActivity.onSettingChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        clearFragments((BaseActivity) mContext, mFragments);
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    protected void setSettingTheme() {
        int themeColor = indexActivity.getThemeColor();
        mToolbar.setBackgroundColor(themeColor);
        mTabLayout.setBackgroundColor(themeColor);
        mBgLayout.setBackgroundColor(SettingPreferenceHelper.INSTANCE.getBACKGROUND_COLOR());
    }
}
